from wtforms import StringField, IntegerField, ValidationError
from wtforms.validators import DataRequired, length, Regexp, Email
from app.libs.enums import ClientTypeEnum
from app.models.user import User
from app.validators.base import BaseForm as Form


class ClientForm(Form):
    account = StringField(validators=[DataRequired(message='账号不能为空'), length(min=5, max=32)])
    secret = StringField()
    type = IntegerField(validators=[DataRequired()])

    def validate_type(self, field):
        try:
            client = ClientTypeEnum(field.data)
            self.type.data = client
        except ValueError as e:
            raise e


class UserEmailForm(ClientForm):
    account = StringField(validators=[
        Email(message='invalidate email')
    ])
    secret = StringField(validators=[
        DataRequired(),
        Regexp(r'^[A-Za-z0-9——*&￥#@]{6,22}$')
    ])
    nickname = StringField(validators=[DataRequired(), length(min=2, max=22)])

    def validate_account(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError